<?php
class UsersController extends AppController {

	var $name = 'Users';
	var $components = array('Email', 'Captcha', 'SystemTicket', 'RequestHandler');
	//var $helpers = array('Captcha');
	var $uses = array('User');
	
	var $paginate = array(
		'User' => array(
	        'limit' => 10,
	        'order' => array(
	        
	            'User.id' => 'DESC'
	        )
		)
    );
    
	/**
	 * User Model
	 *
	 * @var User
	 */
	var $User;
	
	/**
	 * Tyk zadavame spisaka na action-ite s publichen dostyp (action-ite bez authorizaciq)
	 */
	function __initPublicActions() {
		/**
		 * http://groups.google.com/group/cake-php/browse_thread/thread/b8d76622eb8436a9/67aa3a519ce85415?lnk=gst&q=allow+logout
		 * http://groups.google.com/group/cake-php/browse_thread/thread/e4b51058e0727e16/dde2ce06acac9aaf?lnk=gst&q=allow+logout#dde2ce06acac9aaf
		 * http://groups.google.com/group/cake-php/browse_thread/thread/e47a458bb1c5aeb9/40c000b58738ccae?lnk=gst&q=allow+logout#40c000b58738ccae
		 */
		if($this->Auth->user('id')){
			$this->Auth->allow(array(
				'init_db',
				'account_recover',
				'logout',
				'register',
				'securimage',
				'activate',
				'social',
				'index',
				'view',
				'password',
				'edit'
				
			));
		} else {
			$this->Auth->allow(array(
				'init_db',
				'account_recover',
				'logout',
				'register',
				'securimage',
				'activate',
				'social',
				'index'
			));
		}
	}
	
	function __initModelConfigs() {
		$this->User->addExtraValidationSets();
	}
	
	function __sendmail_accountDetails($data) {
		$this->Email->to = $data['User']['email'];
		$this->Email->replyTo = Configure::read('MyApp_Settings.robotMail');
		$this->Email->from = Configure::read('MyApp_Settings.robotMail');
		$this->Email->subject = Configure::read('MyApp_InfoSettings.projectNameForSysEmails').' - '.__d('', 'Акаунт детайли', true).'.';
		$this->Email->template = 'account_details';
		$this->Email->layout = 'default';
		$this->Email->sendAs = 'text';

		$this->set('data', $data);

		return $this->Email->send();
	}
	
	function __sendmail_accountActivation($hash) {
		$theUser = $this->User->findById($this->SystemTicket->get($hash));
		if(is_array($theUser) && is_array($theUser['User'])) {
			$this->Email->to = $theUser['User']['email'];
			$this->Email->replyTo = Configure::read('MyApp_Settings.robotMail');
			$this->Email->from = Configure::read('MyApp_Settings.robotMail');
			$this->Email->subject = Configure::read('MyApp_InfoSettings.projectNameForSysEmails').' - '.__d('', 'Моля, потвърдите Вашият акаунт', true).'.';
			$this->Email->template = 'account_activation';
			$this->Email->layout = 'default';
			$this->Email->sendAs = 'text';
			
			$this->set('activation_url', SITE_WEBROOT.'users/account_activation/'.$hash);
			$this->set('username', $theUser['User']['username']);
			
			return $this->Email->send();
		}
	}
	
	function __sendmail_accountSendRecover($ticket, $email) {
		$this->Email->to = $email;
		$this->Email->replyTo = Configure::read('MyApp_Settings.robotMail');
		$this->Email->from = Configure::read('MyApp_Settings.robotMail');
		$this->Email->subject = Configure::read('MyApp_InfoSettings.projectNameForSysEmails').' - '.__d('', 'Възстановяване на акаунта', true).'.';
		$this->Email->template = 'account_send_recover';
		$this->Email->layout = 'default';
		$this->Email->sendAs = 'text';
		
		$this->set('ticket_link', SITE_WEBROOT.'users/account_activate_recover/'.$ticket);
		
		return $this->Email->send();
	}
	
	function __sendmail_accountActivateRecover($user, $newpass, $email) {
		$this->Email->to = $email;
		$this->Email->replyTo = Configure::read('MyApp_Settings.robotMail');
		$this->Email->from = Configure::read('MyApp_Settings.robotMail');
		$this->Email->subject = Configure::read('MyApp_InfoSettings.projectNameForSysEmails').' - '.__d('', 'Новата Ви парола', true);
		$this->Email->template = 'account_activate_recover';
		$this->Email->layout = 'default';
		$this->Email->sendAs = 'text';
		
		$this->set('user', $user);
		$this->set('newpass', $newpass);
		$this->set('email', $email);
		
		return $this->Email->send();
	}
	
	function beforeFilter() {
        parent::beforeFilter();
        
        $this->__initPublicActions();
        $this->__initModelConfigs();
        
		/*
		 * Use this to provide additional requirements for authentication to succeed.
		 */
		if(Configure::read('MyApp_Users.Settings.accountActivation')) {
			$this->Auth->userScope = array('User.is_active' => 1);
		}
		
		if($this->Auth->user('id') && $this->params['action'] == 'register'){
		        $this->redirect('index');
		}
    }
    
    function init_db() {
    	$this->loadModel('Group');
    	
    	$group =& $this->Group;
    	
    	//------------- root [id=1]
    	$group->id = 1;
    	
    	$this->Acl->allow($group, 'controllers');
    	//------------/ root [id=1]
    	
    	//------------- user [id=2]
    	$group->id = 2;
    	
    	$this->Acl->allow($group, 'controllers/Users/account_activation');
    	$this->Acl->allow($group, 'controllers/Users/account_recover');
    	$this->Acl->allow($group, 'controllers/Users/account_activate_recover');
    	$this->Acl->allow($group, 'controllers/Users/securimage');
    	$this->Acl->allow($group, 'controllers/Users/index');
    	$this->Acl->allow($group, 'controllers/Users/view');
    	$this->Acl->allow($group, 'controllers/Users/register');
    	$this->Acl->allow($group, 'controllers/Users/edit');
    	$this->Acl->allow($group, 'controllers/Users/delete');
    	//------------/ user [id=2]
    	
    	echo "all done";
    	exit;
    }
    
    function account_activation($hash = null) {
		$this->User->id = $this->SystemTicket->get($hash);
		
		if ($this->User->exists()) {
			// Update the active flag in the database
			$this->User->saveField('is_active', 1);
			
			// Let the user know they can now log in!
			$this->Session->setFlash(__d('', 'Вашият акаунт е активиран. Сега можете да влезете.', true));
			
			$this->SystemTicket->del($hash);
			
			$this->redirect(array('admin' => false, 'plugin' => null, 'controller' => 'users', 'action' => 'login'));
		}
		// ako sme podali greshen hash .. togava se zarejda account_activation.ctp
    }
    
	function account_recover() {
		$this->User->set($this->data);
		$this->User->setValidation('account_recover');		
		if(!empty($this->data)) {
				if ($this->User->validates()) {
					$date = base64_encode(date('Y-m-d H:i:s'));
					$password = $this->Auth->password($date);
					$res = parent::sendMailFacebook($this->data['User']['email'], $date, $this->data['User']['username']);
					if($res){
						if($this->User->saveField('password', $password)) {
							$this->Session->setFlash(__d('', 'Please check your email for new password.', true));
							$this->redirect('/');
						} else {
							$this->Session->setFlash(__d('', 'Please try again.', true));
						}
					} else {
						$this->Session->setFlash(__d('', 'We are unable to send password. Please try again.', true));
					}
					
				} 
		}
		
	}
	
	function account_activate_recover($hash = null) {
		$fields_to_save = array('password');
		$this->set('hash', $hash);
		
		/*
		 * ============ CURRENT NAVIGATION CONFIG
		 */
		$siteElementCurrentNavigationData = array(
			'links' => array(
				array('Начало', SITE_WEBROOT)
			),
			'current' => 'Активация'
		);
		$this->set('siteElementCurrentNavigationData', $siteElementCurrentNavigationData);
		/*
		 * ===========/ CURRENT NAVIGATION CONFIG
		 */
		
		if(!empty($this->data)) {
			$theUser = $this->User->findByEmail($this->SystemTicket->get($hash));
			if(is_array($theUser) && is_array($theUser['User'])) {
				$this->User->id = $theUser['User']['id'];
				$user = $theUser['User']['username'];
				
				$newpass = substr(Security::hash(Configure::read('Security.salt').time().$user), 0, 8);
				$this->data['User']['password'] = $this->Auth->password($newpass);
					
				if ($this->User->save($this->data, true, $fields_to_save)) {
					$this->SystemTicket->del($hash);

					$this->__sendmail_accountActivateRecover($user, $newpass, $theUser['User']['email']);
					
					$flashMsg = String::insert(__d('', 'Изпратено Ви е писмо на :User_email с новата парола', true), array('User_email' => $theUser['User']['email']));
					$this->Session->setFlash($flashMsg);
					
					// poneje redirect-vame kym cache-rana stranica togava izpolzvame system_redirects controller-a
					$systemRedirectUrl = "/";
					$this->Session->write('systemRedirectUrl', $systemRedirectUrl);
					$this->redirect(array('admin' => false, 'plugin' => null, 'controller' => 'system_redirects', 'action' => 'system_redirect'));
				}
			}
			else {
				$this->Session->setFlash(__d('', 'Невалидна връзка', true));
				// poneje redirect-vame kym cache-rana stranica togava izpolzvame system_redirects controller-a
				$systemRedirectUrl = "/";
				$this->Session->write('systemRedirectUrl', $systemRedirectUrl);
				$this->redirect(array('admin' => false, 'plugin' => null, 'controller' => 'system_redirects', 'action' => 'system_redirect'));
			}
		}
	}
    
    function securimage($random_number){
        $this->autoLayout = false; //a blank layout

        //override variables set in the component - look in component for full list
        $this->captcha->image_height = 60;
        $this->captcha->image_width = 250;
        $this->captcha->image_bg_color = '#ffffff';
        $this->captcha->line_color = '#cccccc';
        $this->captcha->arc_line_colors = '#999999,#cccccc';
        $this->captcha->code_length = 4;
        $this->captcha->font_size = 20;
        $this->captcha->text_color = '#000000';

        $this->set('captcha_data', $this->captcha->show()); //dynamically creates an image
    }
    
	function login() {
		    $this->User->set($this->data);
	    		$this->User->setValidation('login');

           		 if ($this->Session->read('Auth.User')) { 
           		 	if($this->Session->read('Auth.User.is_active') == 1){
					if( $this->RequestHandler->isAjax()){
						echo json_encode(array('status'=>'error', 'user'=>'notActivated', 'msg'=>'Your account has not activated yet.'));
					} else {
           		 	 		$this->Session->write('Auth.User.socialLogin', 0);           		
	                    			$this->redirect('index');
	                    		}	
           		 	} else {
	           		 	$this->Session->setFlash(__d('', 'Your account has not activated yet.', true));
           		 		$this->RememberMe->delete();
					$this->redirect($this->Auth->logout());
           		 	}
	                } 
	}
	
	function logout() {
		
		if( $this->RequestHandler->isAjax()){
			$this->autoRender =false;
			$this->Auth->logout();
			 echo json_encode(array('status'=>'success'));
		} else {
			$this->Session->setFlash(__d('', 'Вие излязохте успешно.', true));
			$this->RememberMe->delete();
			$this->redirect($this->Auth->logout());
		}
	}
	
	function index() {
		/*
		 * ============ CURRENT NAVIGATION CONFIG
		 */
		$siteElementCurrentNavigationData = array(
			'links' => array(
				array('Начало', SITE_WEBROOT)
			),
			'current' => 'Потребителски панел'
		);
		$this->set('siteElementCurrentNavigationData', $siteElementCurrentNavigationData);
		/*
		 * ===========/ CURRENT NAVIGATION CONFIG
		 */
		 $this->loadModel('Listing');
$listing = $this->Listing->find('all', array('conditions'=>array('OR'=>array('added_by_user_id'=>$this->Auth->user('id'), 'edit_permission'=>$this->Auth->user('id')))));
$this->set('listing', $listing);

$this->loadModel('Review');
$review = $this->Review->find('all', array('conditions'=>array('user_id'=>$this->Auth->user('id'))));
$this->set('review', $review);



	}
	
	function view($id = null) {
	
		if (!$id) {
			$this->Session->setFlash(__d('', 'Невалиден елемент', true));
			$this->redirect(array('admin' => false, 'plugin' => null, 'controller' => 'users', 'action' => 'index'));
		}
		
			$this->set('user', $this->User->read(null, $id));
		
	}
	
	function activate($id = null) { 
		if (!$id) {
			$this->Session->setFlash(__('Invalide User. Token is empty', true));
			$this->redirect(array('action' => 'login'));
		}
		$user = $this->User->find('first', array('conditions'=>array('email_token'=>$id)));
                if($user){
                    $this->User->id = $user['User']['id'];
                    $this->User->saveField('is_active', 1);
                    $this->User->saveField('email_verified', 1);
                    parent::sendActivationMail($user['User']['email'], $user['User']['username']);
                     $this->Auth->login($user);
                    $this->redirect(array('action' => 'login'));
                } else {
			$this->Session->setFlash(__('Invalide User.', true));
			$this->redirect(array('action' => 'login'));
                }

	}
	
	 
	
	function register() {        
		if (!empty($this->data)) {
			if(($this->Captcha->getFirst() + $this->Captcha->getSecond()) == $this->data['User']['captcha_result']) {
			if(trim($this->data['User']['username'])){
				if($this->User->find('first', array('conditions'=>array('username'=>$this->data['User']['username']) ) ) ){
					$this->Session->setFlash(__('Username already taken. Try another.', true));
				} else {
					if(trim($this->data['User']['password_confirm'])){
					 $pass1 = $this->data['User']['password'];
					 $pass2 = $this->Auth->password($this->data['User']['password_confirm']);
					
							if( $pass1 == $pass2 ){
								if(trim($this->data['User']['email'])){
								
										if($this->User->find('first', array('conditions'=>array('email'=>$this->data['User']['email']) ) ) ){
											$this->Session->setFlash(__('User with same email has already register. Please register with another email account.', true));
										} else {
											$this->User->set($this->data);
									
											$this->User->create();
											$this->data['User']['group_id'] = 2;	
											if ($this->User->save($this->data)) {
										                $id = $this->User->id;
										                $token = md5($id);
										                $mail = parent::sendActivationLinkMail($this->data['User']['email'], $token, $this->data['User']['username']);
										                if($mail){
										                    $this->User->id = $id;
										                    $this->User->saveField('email_token', $token);
										                    $this->Session->setFlash(__('Please check your email account to activate.', true));
										                    $this->redirect(array('action' => 'login'));
										                } else {
										                    $this->Session->setFlash(__('The user has been saved', true));
										                    $this->redirect(array('action' => 'login'));
										                }
											} else {
												$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
											}
										}
									} else {
											$this->Session->setFlash(__('The Email must not be empty', true));
									}
							} else {
								$this->Session->setFlash(__('The email must not be empty.', true));
							}
						
					
						} else {
							$this->Session->setFlash(__('The both password field are required', true));
						}
				}
			} else {
				$this->Session->setFlash(__('The username must not be empty', true));
			}
			} else {
				$this->Session->setFlash(__('Please enter the correst captcha value', true));
			}
		} 
		$this->Captcha->__init();

		$this->set('p', $this->Captcha->getFirst());
		$this->set('q', $this->Captcha->getSecond());
	}
	

	
	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__d('', 'Невалиден елемент', true));
			$this->redirect(array('admin' => false, 'plugin' => null, 'controller' => 'users', 'action' => 'index'));
		}
		
		if(($this->Auth->user('id')!=$id) && ($this->Auth->user('group_id')!=1)) {
			/*
			 * teksta na suob6tenieto e ot app_controller.php ... $this->Auth->authError = 'You are not authorized to access that location.';
			 */
			$this->Session->setFlash($this->Auth->authError);
			$this->redirect(array('admin' => false, 'plugin' => null, 'controller' => 'users', 'action' => 'index'));
		} else {
		
			if (!empty($this->data)) {
				if ($this->User->save($this->data)) {
                         	       $this->Session->write('Auth', $this->User->read(null, $this->Auth->User('id')));
					$this->Session->setFlash(__('The user has been saved', true));
					$this->redirect(array('action' => 'index'));
				} else {
					$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
				}
			}
		
			if (empty($this->data)) {
				$this->data = $this->User->read(null, $id);
			}
		}
	}
	
	function password($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid user', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
                    $pass1 = $this->data['User']['password1'];
                    $pass2 = $this->data['User']['password2'];
                    if($pass1 == $pass2){
                        $old_password1 = $this->User->read(null, $this->Auth->User('id'));
                        $old_password1 = $old_password1['User']['password'];
                        $old_password2 = $this->Auth->password($this->data['User']['current_password']); 
                        if($old_password1 == $old_password2){
                            $new_password = $this->Auth->password($pass1);
                            if ($this->User->saveField('password', $new_password)) {
                                    $this->Session->write('Auth', $this->User->read(null, $this->Auth->User('id')));
                                    $this->Session->setFlash(__('The password has been updated', true));
                                    $this->redirect(array('action' => 'index'));
                            } else {
                                    $this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
                            }
                        } else {
                            $this->Session->setFlash(__('Old password entered does not matched', true));
                        }
                    } else {
			$this->Session->setFlash(__('New password entered are not matched', true));
                    }
		}
		if (empty($this->data)) {
			$this->data = $this->User->read(null, $id);
		}
	}

	function social(){
	 	$this->autoRender = false;
 		if($this->Auth->user('username')){
 			if($this->Auth->user('is_active') != 1){
 				$this->Auth->logout();
				echo json_encode(array('status'=>'error','redirect'=>0, 'msg'=>'Your accont is block by admin.', 'admin'=>'active'));
			} else {
 				echo json_encode(array('status'=>'success','redirect'=>0));
 			}
 		} else {
			
				$date = base64_encode(date('Y-m-d H:i:s'));
				$password = $this->Auth->password($date); 
				$e_flag = "";
				
				if(isset($_POST['email']) && !empty($_POST['email'])){
					$data['User'] = array('username'=>$_POST['username'], 'password'=>$password, 'is_active'=>1, 'email'=>$_POST['email'], 'social_login_type'=>1, 'group_id'=>2);	
				} else {
					$data['User'] = array('username'=>$_POST['username'], 'password'=>$password, 'is_active'=>1, 'social_login_type'=>1, 'group_id'=>2);	
					$e_flag = 'Please change your password as we have not get your email from facebook data. The current password is dynamically created.';
				}
				 
				$facebook = $this->User->find('first', array('conditions'=>array('username'=>$data['User']['username'])));
				if($facebook){
				
					if($facebook['User']['is_active'] == 1){
						
						$this->Auth->login($facebook);
						$this->Session->write('Auth.User.socialLogin', 1);
						
						echo json_encode(array('status'=>'success', 'user'=>'old', 'redirect'=>1,  'msg'=>'You have sucessfully login with facebook. You can directly login with facebook user id and password sent on your account too.'));
					} else {
					$this->Auth->logout();
;						echo json_encode(array('status'=>'error', 'redirect'=>0,  'msg'=>'You account has blocked by admin.'));
					}		
					
				} else {
				         
					if($this->User->save($data)){
						$res = parent::sendMailFacebook($data['User']['email'], $date, $data['User']['username']);
						if($res) {
						     $this->Auth->login($data);
						     $this->Session->write('Auth.User.socialLogin', 1);
						     echo json_encode(array('status'=>'success', 'user'=>'new', 'redirect'=>1, 'msg'=>'Please check your email to know the password.'));
						     } else {
							     echo json_encode(array('status'=>'success', 'user'=>'new', 'redirect'=>1, 'msg'=>'We have not found your email in facebook data. So please note your password for direct login. Password: '.$date));
						     }
					} else {
					     echo json_encode(array('status'=>'error'));
					}
				}
			
		}
	}
	
	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__d('', 'Невалиден елемент', true));
			$this->redirect(array('admin' => false, 'plugin' => null, 'controller' => 'users', 'action' => 'index'));
		}
		
		/*
		 * proverka dali tekushtiq potrebitel ima prava za dostyp na tozi record delete/id..
		 * osven ako ne e negoviq ili ne spada kym priviligirovana grupa dostypa se otkazva
		 * 
		 * Priviligirovani grupi koito imat dostyp nezavisimo ot $id-to:
		 * - root
		 */
		// proverka
		if(($this->Auth->user('id')!=$id) && ($this->Auth->user('group_id')!=1)) {
			/*
			 * teksta na suob6tenieto e ot app_controller.php ... $this->Auth->authError = 'You are not authorized to access that location.';
			 */
			$this->Session->setFlash($this->Auth->authError);
			$this->redirect(array('admin' => false, 'plugin' => null, 'controller' => 'users', 'action' => 'index'));
		} else {
			if ($this->User->delete($id)) {
				$upload_msg1 = '';
				
				if($this->SimpleUpload->delete_userMainPicture($id)) {
					$upload_msg1 = 'Потребителската снимка е изтрита успешно'.'<br />';
				} else {
					$upload_msg1 = 'Грешка при изтриването на потребителската снимка'.'<br />';
				}
				
				$this->Session->setFlash($upload_msg1.__d('', 'Потребителят е изтрит успешно.', true));
				// izlizame za da uni4tojim ve4e nevalidnata sesiq i cookie..
				$this->RememberMe->delete();
				$this->redirect($this->Auth->logout());
			}
		}
	}
	//$id => id of listing
	function admin_index($id = null) {
		$this->User->recursive = 0;
		if($id){
			$this->loadModel('Listing');
			$listing = $this->Listing->read(null, $id);
			$users = explode(',', $listing['Listing']['claim_by_users']);
			$this->set('users', $this->paginate(array('User.id'=>$users)));
			$this->set('listing', $listing);
		} else {
			$this->set('users', $this->paginate());
		}
	}
	
	function admin_view($id = null, $type=null) {
		if (!$id) {
			$this->Session->setFlash('Невалиден елемент');
			$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'users', 'action' => 'index'));
		}
		if($type){
			if($type == 'block'){
				$this->admin_block($id);
			} else if($type == 'unblock'){
				$this->admin_unblock($id);
			}
			$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'users', 'action' => 'index'));
		}
		$this->set('user', $this->User->read(null, $id));
	}
	
	function admin_add() {
		$this->User->set($this->data);
		$this->User->setValidation('admin_add');
		$fields_to_save = array('group_id', 'is_active', 'username', 'password', 'email');
		
		if (!empty($this->data)) {
			if ($this->User->validates()) {
				$this->data['User']['password'] = $this->Auth->password($this->data['User']['password_form']);
				// pri administratorka registraciq is_active vednaga set-vame na 1, poneje vse sigurni 4e dannite sa validni
				$this->data['User']['is_active'] = 1;
				
				$this->User->create();
				if ($this->User->save($this->data, true, $fields_to_save)) {
					$this->Session->setFlash('Потребителят е регистриран успешно');
					$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'users', 'action' => 'index'));
				}
			} else {
				$this->Session->setFlash('Потребителят не е регистриран. Моля, опитайте отново.');
			}
		}
		
		$groups = $this->User->Group->find('list');
		$this->set(compact('groups'));
	}
	
	function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash('Невалиден елемент');
			$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'users', 'action' => 'index'));
		}
		
		// dali iskame da smenqme parolata .. ako iskame .. dobavqme dopylnitelni validates
		if((!empty($this->data['User']['new_password_form'])) || (!empty($this->data['User']['new_password_confirm']))) {
			$is_enteredNewPassword = true;
			$this->User->set($this->data);
			$this->User->setValidation('admin_edit_with_newpassword');
		} else {
			$is_enteredNewPassword = false;
			$this->User->set($this->data);
			$this->User->setValidation('admin_edit');
		}
		
		if(Configure::read('MyApp_Users.Settings.usernameEdit_isActive')) {
			$fields_to_save = array('is_active', 'username', 'email');
		} else if(!Configure::read('MyApp_Users.Settings.usernameEdit_isActive')) {
			$fields_to_save = array('is_active', 'email');
		}
		
		$currentUsr = $this->Session->read('MyApp_Users.InfoSettings.authCurrentUser');
		
		// samo za grupata "root" e pozvoleno smenqneto na grupite na user-ite
		if($currentUsr["User"]["group_id"] == 1) {
			array_push($fields_to_save, 'group_id');
		}
		
		if (!empty($this->data)) {
			if($is_enteredNewPassword) {
				$this->data['User']['password'] = $this->Auth->password($this->data['User']['new_password_form']);
				array_push($fields_to_save, 'password');
			}
			
			$this->data["User"] = $this->__trimData($this->data["User"]);
			
			if ($this->User->validates()) {
				if ($this->User->save($this->data, true, $fields_to_save)) {
					$this->Session->setFlash('Потребителят е редактиран успешно.');
					// izlizame za da uni4tojim ve4e nevalidnata sesiq i cookie.. za da sa s novite nastroiki
					$this->RememberMe->delete();
					$this->redirect($this->Auth->logout());
				}
			} else {
					$this->Session->setFlash('Потребителят не е редактиран. Моля, опитайте отново.');
			}
		}
		if (empty($this->data)) {
			$this->data = $this->User->read(null, $id);
		}
		$groups = $this->User->Group->find('list');
		$this->set(compact('groups'));
	}
	
	function admin_delete($id = null, $confirm = false) {
		if (!$id) {
			$this->Session->setFlash('Невалиден елемент');
			$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'users', 'action' => 'index'));
		}
		
		$user = $this->User->read(null, $id);
		$this->set('user', $user);
		
		if($confirm) {
			if ($this->User->delete($id)) {
						$this->Session->setFlash('User deleted');
						$this->redirect(array('admin'=>true, 'plugin'=>false, 'controller'=>'users', 'action'=>'index'));
			}
		}
	}
	
	function admin_block($id = null) {
		if (!$id) {
			$this->Session->setFlash('Невалиден елемент');
			$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'users', 'action' => 'index'));
		}
		$this->User->id = $id;
		if($this->User->saveField('is_active', 0)){
			$this->Session->setFlash('The user has blocked.');
			//$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'users', 'action' => 'index'));
		} else {
			$this->Session->setFlash('Error occured');
		}
		//$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'users', 'action' => 'index'));
	}
	
	function admin_unblock($id = null) {
		if (!$id) {
			$this->Session->setFlash('Невалиден елемент');
			$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'users', 'action' => 'index'));
		}
		$this->User->id = $id;
		if($this->User->saveField('is_active', 1)){
			$this->Session->setFlash('The user has unblocked.');
			
		} else {
			$this->Session->setFlash('Error occured');
		}
		//$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'users', 'action' => 'index'));
	}
}
?>